package com.qixin.modules.version.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.qixin.modules.version.entity.FybxVersionManage;
import com.qixin.modules.version.service.IFybxVersionManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wjb
 * @Date: 2021/12/17/10:21
 * @Description:
 */
@Api(tags="APP版本更新")
@RestController
@RequestMapping("/api/app/version")
@Slf4j
public class APIFybxVersionManageController extends JeecgController<FybxVersionManage, IFybxVersionManageService> {

    @Autowired
    private IFybxVersionManageService fybxVersionManageService;

    /**
     * 分页列表查询
     *
     * @param req
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientId", value = "设备唯一识别码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "appVersion", value = "应用版本号", dataType = "String", paramType = "query"),
    })
    @ApiOperationSupport(ignoreParameters = "params")
    @AutoLog(value = "APP版本更新-检查接口")
    @ApiOperation(value="APP版本更新-检查接口", notes="APP版本更新-检查接口")
    @GetMapping(value = "/checkupdate")
    public Result<?> queryPageList(@RequestParam Map<String, Object> params, HttpServletRequest req) {
        if (!params.containsKey("clientId") && StrUtil.isBlank((String)params.get("clientId"))){
            return Result.error("设备唯一识别码不能为空！");
        }
        if (!params.containsKey("appVersion") && StrUtil.isBlank((String)params.get("appVersion"))){
            return Result.error("应用版本号不能为空！");
        }

        //设备唯一识别码
        String clientId = params.get("clientId").toString();
        //当前版本号
        Integer appVersion =  Integer.valueOf(params.get("appVersion").toString()) ;
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());

        Map<String, Object> rsmap = new HashMap<>();

        rsmap.put("isUpdate",false);
        rsmap.put("apkPath","");
        rsmap.put("type",1);

        //返回需要更新的APK包路径
        String updateApkPath = null ;
        //是否需要更新
        boolean isUpdate = true ;

        //全部用户 更新的版本
        QueryWrapper<FybxVersionManage> batchUpdateQueryWrapper = new QueryWrapper<FybxVersionManage>();
        batchUpdateQueryWrapper.eq("state",1)  // state 发布状态(0,未发布,1发布)
                .eq("push_object",1)    // 发布对象(0,批定用户,1,全部用户)
                .le("issue_time",date) // 发布时间
                .gt("app_version",appVersion) // 内部版本号
                .orderByDesc("app_version")
                .last("LIMIT 1");
        List<FybxVersionManage> batchUpdateList = fybxVersionManageService.list(batchUpdateQueryWrapper);
        if (batchUpdateList != null && batchUpdateList.size() > 0){
            FybxVersionManage batchUpdateVersion = batchUpdateList.get(0);
            rsmap.put("isUpdate",true);
            rsmap.put("apkPath",batchUpdateVersion.getApkPath());
            rsmap.put("content",batchUpdateVersion.getContent());
            rsmap.put("type",batchUpdateVersion.getType());
            return Result.OK(rsmap);
        }else{
            //指定用户 更新的版本
            QueryWrapper<FybxVersionManage> allUpdateQueryWrapper = new QueryWrapper<FybxVersionManage>();
            allUpdateQueryWrapper.eq("state",1)  //state 发布状态(0,未发布,1发布)
                    .eq("push_object",0) // 发布对象(0,批定用户,1,全部用户)
                    .like("object_id", clientId) // 发布对象Id
                    .le("issue_time",date) // 发布时间
                    .gt("app_version",appVersion) // 内部版本号
                    .orderByDesc("app_version")
                    .last("LIMIT 1");
            List<FybxVersionManage> allUpdateList = fybxVersionManageService.list(allUpdateQueryWrapper);
            if ( allUpdateList != null && allUpdateList.size() > 0){
                FybxVersionManage allUpdateVersion = allUpdateList.get(0);
                rsmap.put("isUpdate",true);
                rsmap.put("apkPath",allUpdateVersion.getApkPath());
                rsmap.put("content",allUpdateVersion.getContent());
                rsmap.put("type",allUpdateVersion.getType());
                return Result.OK(rsmap);
            }
        }
        return Result.OK(rsmap);
    }


    @ApiOperation(value="查询最新版本app下载地址", notes="查询最新版本app下载地址")
    @GetMapping(value = "/download")
    public void findAppAddress(HttpServletResponse response) throws IOException {
        String address = fybxVersionManageService.findAppAddress();
        String ip = fybxVersionManageService.selectOutNetIP();
        address = ip + address;
        response.sendRedirect(address);
    }
}
